# -*- encoding=UTF-8 -*-

from ganstore import app, db
from models import Image, User, Tread, Seller, Rankrecord, PolicyImage, Policyrecord
from flask import request
import json, time


# 首页
@app.route('/api/home/index/', methods=['GET'])
def home():
    images = Image.query.filter_by(tread_id=1).all()
    hotTread = Tread.query.limit(10).all()
    hotSeller = Seller.query.limit(10).all()
    map = {}
    banner = []
    for image in images:
        imgvo = {'id': image.tread_id, 'url': image.url}
        banner.append(imgvo)
    hotTreads = []
    for tread in hotTread:
        treadvo = {'id': tread.id, 'name': tread.name, 'hotTreadUrl': tread.images[0].url}
        hotTreads.append(treadvo)
    hotSellers = []
    for seller in hotSeller:
        tread = Tread.query.filter_by(seller_id=seller.id).first()
        image = Image.query.filter_by(tread_id=tread.id).first()
        sellervo = {'id': seller.id, 'name': seller.name, 'address': seller.address,
                    'contact': seller.contact, 'phone': seller.phone, 'imgUrl': image.url,
                    'treadName': tread.name, 'treadSpec': get_spec(tread.id),
                    'treadPrice': tread.price}
        hotSellers.append(sellervo)
    map['banner'] = banner
    map['hotTreads'] = hotTreads
    map['hotSellers'] = hotSellers
    return json.dumps(map)


def get_spec(tread_id):
    tread = Tread.query.filter_by(id=tread_id).first()
    return str(tread.tread_wide) + str('/') + str(tread.flat_radio) + str('R') + str(tread.diameter);


# 商家页面
@app.route('/api/seller/getlist/', methods=['GET', 'POST'])
def seller():
    page = request.values.get('page')
    page = int(page)
    paginate = Seller.query.limit(5).offset((page - 1) * 5).all()
    map = {}
    sellers = []
    for seller in paginate:
        tread = Tread.query.filter_by(seller_id=seller.id).first()
        image = Image.query.filter_by(tread_id=tread.id).first()
        sellervo = {'id': seller.id, 'name': seller.name, 'address': seller.address,
                    'contact': seller.contact, 'phone': seller.phone, 'imgUrl': image.url,
                    'treadName': tread.name, 'treadSpec': get_spec(tread.id),
                    'treadPrice': tread.price}
        sellers.append(sellervo)

    map['sellers'] = sellers
    return json.dumps(map)


# 商家详情页
@app.route('/api/seller/index/', methods=['GET', 'POST'])
def seller_datails():
    seller_id = request.values.get('seller_id')
    seller_id = int(seller_id)
    treads = Tread.query.filter_by(seller_id=seller_id).all()
    seller = Seller.query.filter_by(id=seller_id).first()
    map = {}
    treadsAll = []
    sellerAll = []
    sellerAll.append({
        'id': seller_id, 'name': seller.name, 'address': seller.address, 'contact': seller.contact,
        'phone': seller.phone
    })
    for tread in treads:
        image = Image.query.filter_by(tread_id=tread.id).first()
        treadvo = {'id': tread.id, 'treadName': tread.name, 'treadSpec': get_spec(tread.id),
                   'price': tread.price, 'imgUrl': image.url}
        treadsAll.append(treadvo)
    map['treads'] = treadsAll
    map['sellers'] = sellerAll
    return json.dumps(map)


# 商品详情
@app.route('/api/product/index/', methods=['GET', 'POST'])
def product():
    pro_id = request.values.get('pro_id')
    pro_id = int(pro_id)
    images = Image.query.filter_by(tread_id=pro_id).all()
    map = {}
    imagesUrl = []
    sellers = []
    treads = []
    imagesUrl.append({'id': pro_id})
    for image in images:
        treadvo = {'imgUrl': image.url}
        imagesUrl.append(treadvo)

    tread = Tread.query.filter_by(id=pro_id).first()
    treadvo = {'id': pro_id, 'treadName': tread.name, 'treadSpec': get_spec(pro_id),
               'price': tread.price}
    treads.append(treadvo)
    seller = Seller.query.filter_by(id=tread.seller_id).first()
    sellervo = {'id': seller.id, 'name': seller.name, 'address': seller.address,
                'contact': seller.contact, 'phone': seller.phone}
    sellers.append(sellervo)
    map['images'] = imagesUrl
    map['sellers'] = sellers
    map['treads'] = treads
    return json.dumps(map)


# 商品页面
@app.route('/api/goods/getlist/', methods=['GET', 'POST'])
def goods():
    page = request.values.get('page')
    page = int(page)
    paginate = Tread.query.limit(5).offset((page - 1) * 5).all()
    map = {}
    goods = []
    for tread in paginate:
        seller = Seller.query.filter_by(id=tread.seller_id).first()
        image = Image.query.filter_by(tread_id=tread.id).first()
        treadvo = {'id': tread.id, 'price': tread.price, 'spec': get_spec(tread.id),
                   'name': tread.name, 'address': seller.address, 'imgUrl': image.url}
        goods.append(treadvo)

    map['goods'] = goods
    return json.dumps(map)


# 搜索
@app.route('/api/search/index/', methods=['GET', 'POST'])
def search():
    treadwide = request.values.get('treadwide')
    flatradio = request.values.get('flatradio')
    diameter = request.values.get('diameter')
    search_value = request.values.get('search_value')
    # print treadwide, flatradio, diameter
    if treadwide is not None:
        treads = Tread.query.filter_by(tread_wide=treadwide).filter_by(flat_radio=flatradio).filter_by(
            diameter=diameter).all()
        goods = []
        for tread in treads:
            seller = Seller.query.filter_by(id=tread.seller_id).first()
            image = Image.query.filter_by(tread_id=tread.id).first()
            treadvo = {'id': tread.id, 'price': tread.price, 'spec': get_spec(tread.id),
                       'name': tread.name, 'address': seller.address, 'imgUrl': image.url}
            goods.append(treadvo)
        map = {}
        map['search'] = goods
        return json.dumps(map)

    if search_value is not None:
        sellers = Seller.query.filter(Seller.name.endswith(search_value)).all()
        sellerAll = []
        map = {}
        for seller in sellers:
            tread = Tread.query.filter_by(seller_id=seller.id).first()
            image = Image.query.filter_by(tread_id=tread.id).first()
            sellervo = {'id': seller.id, 'name': seller.name, 'address': seller.address,
                        'contact': seller.contact, 'phone': seller.phone, 'imgUrl': image.url,
                        'treadName': tread.name, 'treadSpec': get_spec(tread.id),
                        'treadPrice': tread.price}
            sellerAll.append(sellervo)
        map['sellers'] = sellerAll
        return json.dumps(map)


# 我的
@app.route('/api/my/index/', methods=['GET', 'POST'])
def my():
    user_name = request.values.get('user_name')
    print user_name
    user = User.query.filter_by(username=user_name).first()
    userAll = []
    map = {}
    uservo = {'id': user.id, 'deadline': str(user.vip_deadline)}
    userAll.append(uservo)
    map['my'] = userAll
    return json.dumps(map)


# vip
@app.route('/api/vip/index/', methods=['GET', 'POST'])
def vip():
    vip_time = request.values.get('vip_time')
    vip_time = int(vip_time)
    user_id = request.values.get('user_id')
    vip_level = request.values.get('vip_level')
    print vip_time, vip_level, user_id
    now = time.time()
    timestamp = now + vip_time * 30 * 1 * 24 * 60 * 60;
    # 转换成localtime
    time_local = time.localtime(timestamp)
    # 转换成新的时间格式
    deadline = time.strftime("%Y-%m-%d %H:%M:%S", time_local)
    # print deadline
    user_confirm = User.query.filter_by(username=user_id).first()
    map = {}
    vip = []
    if user_confirm != None:
        user_confirm.vip_level = vip_level
        user_confirm.vip_deadline = deadline
        db.session.commit()
        vip.append({'userId': user_id, 'vipLevel': vip_level, 'deadline': deadline})
        map['vip'] = vip
        return json.dumps(map)
    user = User(user_id, 'zz')
    user.vip_level = vip_level
    user.vip_deadline = deadline
    db.session.add(user)
    db.session.commit()
    vipvo = {'userId': user_id, 'vipLevel': vip_level, 'deadline': deadline}
    vip.append(vipvo)
    map['vip'] = vip
    return json.dumps(map)


# 积分
@app.route('/api/rank/index/', methods=['GET', 'POST'])
def rank():
    rank_records = Rankrecord.query.filter_by(user_id=1).all()
    map = {}
    score_records = []
    for rank_record in rank_records:
        rankvo = {'id': rank_record.id, 'record_add_reduce': rank_record.record_add_reduce,
                  'record_event': rank_record.record_event, 'record_change': rank_record.record_change,
                  'datetime': str(rank_record.created_date)}
        score_records.append(rankvo)
    map['score'] = score_records
    return json.dumps(map)


# 保单记录
@app.route('/api/policy/index/', methods=['GET', 'POST'])
def policy():
    policy_records = Policyrecord.query.filter_by(user_id=1).all()
    map = {}
    policy_records_all = []
    for policy_record in policy_records:
        user = User.query.filter_by(id=policy_record.user_id).first()
        policyvo = {'id': policy_record.id, 'name': user.username,
                    'car_num': policy_record.car_num, 'policy_event': policy_record.policy_event,
                    'datetime': str(policy_record.created_datetime)}
        policy_records_all.append(policyvo)
    map['policy_record'] = policy_records_all
    return json.dumps(map)


# 保单详情
@app.route('/api/policydetails/index/', methods=['GET', 'POST'])
def policy_datails():
    policy_id = request.values.get('policy_id')
    policy_record = Policyrecord.query.filter_by(id=policy_id).first()
    policy_images = PolicyImage.query.filter_by(policy_id=policy_id).all()
    map = {}
    policy_details_all = []
    policy_images_all = []
    user = User.query.filter_by(id=policy_record.user_id).first()
    policyvo = {'id': policy_record.id, 'name': user.username,
                'car_num': policy_record.car_num, 'phone': user.phone,
                'event': policy_record.policy_event}
    policy_details_all.append(policyvo)
    for policy_image in policy_images:
        imagevo = {'id': policy_image.id, 'imgUrl': policy_image.url}
        policy_images_all.append(imagevo)
    map['policy_detail'] = policy_details_all
    map['policy_images'] = policy_images_all
    return json.dumps(map)
